package com.bbcare.followup.plat.service.impl;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.followup.plat.entity.PtSmsCurrent;
import com.bbcare.followup.plat.service.ISmsService;
import com.bbcare.followup.plat.store.ibatis.IPtSmsRdDao;

@Service
public class SmsService implements ISmsService {
	private final Log logger = LogFactory.getLog(PatientqueryCardService.class);

	@Autowired
	private IPtSmsRdDao IPtSmsRdDao;

	/*
	 * 短信发送具体实现方法
	 */
	@SuppressWarnings("deprecation")
	@Override
	public Map<String, Object> saveSmsInfo(Map<String, Object> mapIn) throws Exception {
		if(null == mapIn){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"发送短信传入参数为空");
		}

		String  smsType =(String) mapIn.get("smsType");
		String  phoneNo =(String) mapIn.get("phoneNo");
		String  smsContent =(String) mapIn.get("smsText");
		String	updateTime = (String) mapIn.get("updateTime");
		String	updateAccept = (String) mapIn.get("updateAccept");
		String	authorId = (String) mapIn.get("authorId");
		String	ptSchemeid = (String) mapIn.get("ptSchemeid");
		String	queueId = (String) mapIn.get("queueId");
		String	taskId = (String) mapIn.get("taskId");
		String	userId = (String) mapIn.get("userId");
		String	ruleType = (String) mapIn.get("ruleType");
		String	taskName = (String) mapIn.get("taskName");
		String	tenantId = (String) mapIn.get("tenantId");
		String ruleId= (String) mapIn.get("ruleId");
		if(StringUtils.isEmpty(smsType)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"发送短信必传参数smsType为空");
		}
		if(StringUtils.isEmpty(phoneNo)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"发送短信必传参数phoneNo为空");
		}
		if(StringUtils.isEmpty(smsContent)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"发送短信必传参数smsContent为空");
		}

		Map<String, Object> paraMap = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("phoneNo", phoneNo);
		map.put("smsType", smsType);

		// 每天同一个号码，同种类型的短信最多10条
		String verifyCode = "";
		String smsText = smsContent; // 短信验证码前半部分文字

		if (smsType.equals("01") || smsType.equals("02") || smsType.equals("04") || smsType.equals("07")) {
			int smsCount = IPtSmsRdDao.querySmsCountByNowDayMpSmsType(map);
			logger.info("smsCount : " + smsCount);
			if (smsCount > 0 && smsCount < 3) {
				List<Map<String, Object>> smsList = IPtSmsRdDao.getLastSms(map);
				if (smsList != null && smsList.size() > 0) {
					Timestamp sendTime = (Timestamp) smsList.get(0).get("create_time");
					throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
							"验证码已发送，请勿多次获取(验证码发送时间：" + sendTime.getHours() + "点" + sendTime.getMinutes() + "分左右)");
				}
			} else if (smsCount >= 3) {
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
						"尊敬的用户！您今天的短信次数已达到最大值，请明天操作！");
			}
			verifyCode = ToolUtils.getRandom(4);
			smsText = verifyCode;  //阿里注册码  有短信模板 只需要传验证码
		}

		// 重新发送注册验证短信时将原短信设置为失效
		if (StringUtils.isEmpty(updateTime)) {
			updateTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
		}
		if (StringUtils.isEmpty(updateAccept)) {
			updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
		}
		// 发送主机ip
		String ipAddress = "";
		try {
			InetAddress netAddress = InetAddress.getLocalHost();
			ipAddress = netAddress.getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			ipAddress = "";
		}
		// 保存短信记录表
		/*msg = "【贝生医疗】您的短信验证码为" + msg + "有效期5分钟";
		paraMap.put("phoneNo", phoneNo); // 手机号
		paraMap.put("smsText", smsText); // 短信内容
		paraMap.put("smsType", smsType); // 短信类型:01-注册验证类短信;02-找回登陆密码;
		paraMap.put("verifyCode", verifyCode); // 验证码
		paraMap.put("verifyStatus", "00"); // 验证状态:00-默认状态;01-待验证;02-已验证;03-失效;
		paraMap.put("checkStatus", "01");// 状态:01-待发送;02-发送完成;03-发送失败;
		 */
		String ptSmsId = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PT_SMS_RD_ID);
		PtSmsCurrent psrVo = new PtSmsCurrent();
		psrVo.setCheckStatus("01");
		psrVo.setCreateAuthor(authorId);
		psrVo.setCreateTime(new Date());
		psrVo.setId(ptSmsId);
		psrVo.setPhoneNo(phoneNo);
		psrVo.setPtSchemeid(ptSchemeid);
		psrVo.setQueueId(queueId);
		psrVo.setSendIp(ipAddress);
		psrVo.setSmsText(smsText);
		psrVo.setSmsType(smsType);
		psrVo.setTaskId(taskId);
		psrVo.setUpdateAccept(updateAccept);
		psrVo.setUserId(userId);
		psrVo.setVerifyCode(verifyCode);
		psrVo.setVerifyStatus("00");
		psrVo.setInformType(ruleType);
		psrVo.setTaskName(taskName);
		psrVo.setSendStatus(Constants.SMS_STATUS_SEND_READY); //0 待发送   1发送成功 2发送失败 5发送中
		psrVo.setTenantId(tenantId);
		psrVo.setRuleId(ruleId);

		logger.info("paraMap :" + paraMap.toString());
		IPtSmsRdDao.savePtSmsCurrent(psrVo);
		return null;
	}

	@Override
	public List<Map<String, Object>> selectSendFailSmsList(
			Map<String, Object> paramMap) throws Exception {
		int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 20;

		paramMap.put("start", rows*(page-1));
		paramMap.put("end", rows);
		paramMap.put("userStatus",Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
		paramMap.put("ruleStatus",Constants.TABLE_RECORD_STATUS_NOMAL);
		if(StringUtils.isEmpty(paramMap.get("sendStatus"))){
			paramMap.put("sendStatus",Constants.PT_INFORM_SMS_STATUS_FAILED); //默认查询发送失败的短信
		}
		paramMap.put("taskStatus",Constants.PATIENT_TASK_STATUS_FINISH);//查询任务过期或任务未完成的
		List<Map<String, Object>> list = IPtSmsRdDao.selectSendFailSms(paramMap);
		if(!CollectionUtils.isEmpty(list)){
			for(int i =0;i<list.size();i++){
				Map<String,Object> map = list.get(i);
				if(null != map.get("createTime")){
					list.get(i).put("createTime",map.get("createTime").toString());
				}
			}
		}

		return list;
	}

	@Override
	public int selectSendFailSmsCount(Map<String, Object> mapIn)
			throws Exception {
		int count = IPtSmsRdDao.selectSendFailSmsCount(mapIn);
		return count;
	}


}
